let products = [
  {
    id: 1001,
    name: "你是谁",
    img: "./img/2.jpg",
    price: 35.86,
  },
  {
    id: 1002,
    name: "我是谁",
    img: "./img/2.jpg",
    price: 35.45,
  },
  {
    id: 1003,
    name: "他是谁",
    img: "./img/2.jpg",
    price: 45.89,
  },
  {
    id: 1004,
    name: "谁是谁",
    img: "./img/2.jpg",
    price: 75.65,
  },
  {
    id: 1005,
    name: "她是谁",
    img: "./img/2.jpg",
    price: 66.99,
  },
  {
    id: 1006,
    name: "我是我",
    img: "./img/1.jpg",
    price: 35.86,
  },
  {
    id: 1007,
    name: "你是你",
    img: "./img/1.jpg",
    price: 35.45,
  },
  {
    id: 1008,
    name: "他是他",
    img: "./img/1.jpg",
    price: 45.89,
  },
  {
    id: 1009,
    name: "她不是她",
    img: "./img/1.jpg",
    price: 75.65,
  },
  {
    id: 1010,
    name: "谁就是谁",
    img: "./img/1.jpg",
    price: 66.99,
  },
];
const container = document.querySelector(".container");
//添加图书
function showBook() {
  let str = "";
  products.forEach((item, index) => {
    let bookStr = ` 
  <div class="item">
  <img src="${item.img}">
  <div class="name">书名：${item.name}</div>
  <p>介绍：好好好好好好好好爱护，一定要啊不是吧真的吗，哈哈哈，以你的心诠释我的爱....</p>
  价格:￥<span>${item.price}</span>
  <button type="button" date-index='${item.id}' >添加到购物车</button>
</div> `;
    str += bookStr;
  });
  container.innerHTML = str;
}
showBook();
container.addEventListener("click", (e) => {
  e = e || window.event;
  let target = e.target || e.srcElement;
  if (target.nodeName == "BUTTON") {
    let id = target.getAttribute("date-index");
    console.log(id);
    let product=products.find(item=>item.id==id)
    product={
        ...product,
        num:1,
        singlePrice:product.price,
        state:false
    }
    console.log(product);
    //拿出数组
  let  Arr=JSON.parse(localStorage.getItem("CartList"))  || []
  console.log(Arr)
  let newProduct=Arr.find(item=>item.id==product.id)
  if(newProduct) newProduct.num++
  else  Arr.push(product)
  localStorage.setItem('CartList',JSON.stringify(Arr))
  }
});
